//
//  UIImage+Extension.swift
//  SK_BasePrivateProject
//
//  Created by Chenjing on 2018/7/5.
//  Copyright © 2018年 leapp. All rights reserved.
//

import UIKit

extension UIImage {
    
    /**
     *  通过颜色和尺寸生成图片
     */
    public convenience init?(color: UIColor, size: CGSize = CGSize.init(width: 1.0, height: 1.0)) {
        
        UIGraphicsBeginImageContextWithOptions(size, true, UIScreen.main.scale)
        defer {
            UIGraphicsEndImageContext()
        }
        
        let context = UIGraphicsGetCurrentContext()
        context?.setFillColor(color.cgColor)
        context?.fill(CGRect.init(origin: CGPoint.zero, size: size))
        context?.setShouldAntialias(true)
        
        let image = UIGraphicsGetImageFromCurrentImageContext()
        guard let cgImage = image?.cgImage else {
            self.init()
            return nil
        }
        self.init(cgImage: cgImage)
    }
    
    /**
     *  图片设置圆角,传入圆角半径
     */
    public func roundImage(byRoundingCorners: UIRectCorner = UIRectCorner.allCorners, cornerRadius: CGFloat) -> UIImage? {
        return roundImage(byRoundingCorners: byRoundingCorners, cornerSize: CGSize.init(width: cornerRadius, height: cornerRadius))
    }
    
    /**
     *  图片设置圆角,传入圆角Size
     */
    public func roundImage(byRoundingCorners: UIRectCorner = UIRectCorner.allCorners, cornerSize: CGSize) -> UIImage? {
        
        let imageRect = CGRect.init(origin: CGPoint.zero, size: size)
        UIGraphicsBeginImageContextWithOptions(size, false, UIScreen.main.scale)
        defer {
            UIGraphicsEndImageContext()
        }
        let context = UIGraphicsGetCurrentContext()
        guard context != nil else {
            return nil
        }
        context?.setShouldAntialias(true)
        let bezeirPath = UIBezierPath.init(roundedRect: imageRect, byRoundingCorners: byRoundingCorners, cornerRadii: cornerSize)
        bezeirPath.close()
        bezeirPath.addClip()
        self.draw(in: imageRect)
        return UIGraphicsGetImageFromCurrentImageContext()
    }
    
    /**
     *  图片缩放
     */
    public func scaleTo(size targetSize: CGSize) -> UIImage? {
        let srcSize = self.size
        if __CGSizeEqualToSize(srcSize, targetSize) {
            return self
        }
        
        let scaleRatio = targetSize.width / srcSize.width
        var dstSize = CGSize(width: targetSize.width, height: targetSize.height)
        let orientation = self.imageOrientation
        var transform = CGAffineTransform.identity
        switch orientation {
        case .up:
            transform = CGAffineTransform.identity
        case .upMirrored:
            transform = CGAffineTransform(translationX: srcSize.width, y: 0.0)
            transform = transform.scaledBy(x: -1.0, y: 1.0)
        case .down:
            transform = CGAffineTransform(translationX: srcSize.width, y: srcSize.height)
            transform = transform.scaledBy(x: 1.0, y: CGFloat(CGFloat.pi))
        case .downMirrored:
            transform = CGAffineTransform(translationX: 0.0, y: srcSize.height)
            transform = transform.scaledBy(x: 1.0, y: -1.0)
        case .leftMirrored:
            dstSize = CGSize(width: dstSize.height, height: dstSize.width)
            transform = CGAffineTransform(translationX: srcSize.height, y: srcSize.width)
            transform = transform.scaledBy(x: -1.0, y: 1.0)
            transform = transform.rotated(by: CGFloat(3.0) * CGFloat(CGFloat.pi/2))
        case .left:
            dstSize = CGSize(width: dstSize.height, height: dstSize.width)
            transform = CGAffineTransform(translationX: 0.0, y: srcSize.width)
            transform = transform.rotated(by: CGFloat(3.0) * CGFloat(CGFloat.pi/2))
        case .rightMirrored:
            dstSize = CGSize(width: dstSize.height, height: dstSize.width)
            transform = CGAffineTransform(scaleX: -1.0, y: 1.0)
            transform = transform.rotated(by:  CGFloat(CGFloat.pi/2))
        default:
            dstSize = CGSize(width: dstSize.height, height: dstSize.width)
            transform = CGAffineTransform(translationX: srcSize.height, y: 0.0)
            transform = transform.rotated(by:  CGFloat(CGFloat.pi/2))
        }
        
        UIGraphicsBeginImageContextWithOptions(dstSize, false, scale)
        defer {
            UIGraphicsEndImageContext()
        }
        let context = UIGraphicsGetCurrentContext()
        guard context != nil else {
            return nil
        }
        context?.setShouldAntialias(true)
        if orientation == UIImageOrientation.right || orientation == UIImageOrientation.left {
            context?.scaleBy(x: -scaleRatio, y: scaleRatio)
            context?.translateBy(x: -srcSize.height, y: 0)
        }
        else {
            context?.scaleBy(x: scaleRatio, y: -scaleRatio)
            context?.translateBy(x: 0, y: -srcSize.height)
        }
        context?.concatenate(transform)
        guard let cgImage = self.cgImage else {
            return nil
        }
        context?.draw(cgImage, in: CGRect(x: 0, y: 0, width: srcSize.width, height: srcSize.height))
        return UIGraphicsGetImageFromCurrentImageContext()
    }
    
    /**
     *  剪裁图片的指定部分
     */
    class public func cutImage(image: UIImage, rect: CGRect) -> UIImage {
        UIGraphicsBeginImageContext(rect.size)
        image.draw(in: rect)
        let newImage: UIImage! = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return newImage;
    }
    
    /**
     *  将图片缩放成指定尺寸（多余部分自动删除）
     */
    class public func cutImageSaleTo(image: UIImage, size: CGSize) -> UIImage {
        //计算比例
        let aspectWidth  = size.width/size.width
        let aspectHeight = size.height/size.height
        let aspectRatio = max(aspectWidth, aspectHeight)
        
        //图片绘制区域
        var scaledImageRect = CGRect.zero
        scaledImageRect.size.width  = size.width * aspectRatio
        scaledImageRect.size.height = size.height * aspectRatio
        scaledImageRect.origin.x    = (size.width - size.width * aspectRatio) / 2.0
        scaledImageRect.origin.y    = (size.height - size.height * aspectRatio) / 2.0
        
        //绘制并获取最终图片
        UIGraphicsBeginImageContext(size)
        image.draw(in: scaledImageRect)
        let scaledImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        
        return scaledImage!
    }
    
    /**
     *  压缩图片
     */
    class func compressImage(image: UIImage, maxLength: Int) -> UIImage {
        
        let dataLength = UIImageJPEGRepresentation(image, 1.0)?.count
        if dataLength! <= maxLength {
            return image
        }
        
        var compressedImage: UIImage! = image;
        
        var data: Data? = UIImageJPEGRepresentation(image, 0.98);
        compressedImage = UIImage.init(data: data!)
        if data!.count <= maxLength {
            return compressedImage;
        }
        
        let multiple : CGFloat = CGFloat(maxLength/data!.count)
        let ratio: CGFloat = 0.9 * multiple
        let size = CGSize.init(width: compressedImage.size.width * ratio, height: compressedImage.size.height * ratio)
        
        UIGraphicsBeginImageContext(size)
        compressedImage.draw(in: CGRect.init(origin: CGPoint.zero, size: size))
        compressedImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        data = UIImageJPEGRepresentation(compressedImage, 1.0)
        if data!.count <= maxLength {
            return compressedImage;
        } else {
            return UIImage.compressImage(image:compressedImage ,maxLength:maxLength)
        }
    }
    
    func scaleToSize(_ size :CGSize) -> UIImage?{
        
        UIGraphicsBeginImageContext(size)
        
        self.draw(in: CGRect(x: 0, y: 0, width: size.width, height: size.height))
        
        let newImg = UIGraphicsGetImageFromCurrentImageContext()
        
        UIGraphicsEndImageContext()
        
        return newImg
    }
    
    /**
     *  截频
     */
    class func captureImage(view: UIView) -> UIImage {
        
        // 参数①：截屏区域  参数②：是否透明  参数③：清晰度
        UIGraphicsBeginImageContextWithOptions(view.frame.size, true, UIScreen.main.scale)
        view.layer.render(in: UIGraphicsGetCurrentContext()!)
        let image:UIImage = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext();
        return image;
    }
    
    /**
     *  截频， 长图
     */
    class func captureFullImage(scrollView: UIScrollView) -> UIImage {
        
        // 记录当前的scrollView的偏移量和坐标
        let currentContentOffSet:CGPoint = scrollView.contentOffset
        let currentFrame:CGRect = scrollView.frame;
        
        // 设置为zero和相应的坐标
        scrollView.contentOffset = CGPoint.zero
        scrollView.frame = CGRect.init(x: 0, y: 0, width: scrollView.frame.size.width, height: scrollView.frame.size.height)
        
        // 参数①：截屏区域  参数②：是否透明  参数③：清晰度
        UIGraphicsBeginImageContextWithOptions(scrollView.contentSize, true, UIScreen.main.scale)
        scrollView.layer.render(in: UIGraphicsGetCurrentContext()!)
        let image:UIImage = UIGraphicsGetImageFromCurrentImageContext()!
        
        // 重新设置原来的参数
        scrollView.contentOffset = currentContentOffSet
        scrollView.frame = currentFrame
        
        UIGraphicsEndImageContext();
        
        return image;
    }
    
}

